import Taro, {Component} from '@tarojs/taro';
// 引入 WebView 组件
import {Image, View} from '@tarojs/components';
import QR from 'qrcode-base64';
import HxPage from "../../components/hxPage/hxPage";
import './index.scss';
import {HxPost} from "../../service/http";

export default class H5Page extends Component<any, any> {
    timer = 0;

    constructor() {
        super();
        this.state = {
            qrCode: '',
            qrCodeExpireTime: 30,
        };
    }

    componentWillUnmount() {
        Taro.setScreenBrightness({value: Taro.getStorageSync('ScreenBrightness')})
        clearTimeout(this.timer)
    }

    componentWillMount() {
        Taro.getScreenBrightness()
            .then((res) => {
                console.log(res.value)
                Taro.setStorageSync('ScreenBrightness', res.value)
                Taro.setScreenBrightness({value: 1})
            })
    }

    componentDidMount() {
        this.refresh()
    }

    refresh() {
        clearTimeout(this.timer);
        Taro.showLoading({title: '加载中...', mask: true})
            .then(() => {
                return HxPost('qrCode', {})
            })
            .then((data) => {
                this.setState({
                    qrCode: QR.drawImg(data.qrCode, {
                        typeNumber: 4,
                        errorCorrectLevel: 'M',
                        size: 500
                    }),
                    qrCodeExpireTime: data.qrCodeExpireTime,
                });
                Taro.hideLoading();
                this.timeFun();
            })
            .catch((err) => {
                console.log(err)
                Taro.hideLoading();
                Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 2 * 1000}).catch();
            })
    }

    timeFun() {
        clearTimeout(this.timer)
        // @ts-ignore
        this.timer = setTimeout(() => {
            this.refresh();
        }, this.state['qrCodeExpireTime'] * 1000)
    }

    render() {
        const {qrCode, qrCodeExpireTime} = this.state;
        return (
            <HxPage>
                <View className='qrCode'>
                    {
                        qrCode === '' ?
                            <View className='qrCode_empty'>
                                <View>网络延迟或请求超时</View>
                                <View className='qrCode_empty_btn' onClick={this.refresh.bind(this)}>点击刷新</View>
                            </View>
                            :
                            <Image className='qrcode' src={qrCode} mode="aspectFit" style='width:100%;'/>
                    }
                    <View className='qrCode_tips' onClick={this.refresh.bind(this)}>
                        <View className='icon iconfont icon-shuaxin'/>间隔{qrCodeExpireTime}秒自动刷新
                    </View>
                </View>
            </HxPage>
        );
    }
}
